const Router = require("koa-router")
const router = new Router()
const bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
const gravatar = require('gravatar');
const tools = require('../../config/tools');
const keys = require('../../config/keys');
const passport = require('koa-passport')



// 引入User
const User = require("../../models/User")
// 引入input验证
const validateRegisterInput = require("../../validation/register")
const validateLoginInput = require("../../validation/login")


/**
 * @route GET api/users/test
 * @desc 测试接口地址
 * @access 接口公开的
 */

router.get('/test', async ctx => {
    ctx.status = 200
    ctx.body = {
        msg: 'test is ok'
    }
})

/**
 * @route POST api/users/register
 * @desc 用户注册接口
 * @access 接口公开的
 */
router.post('/register', async ctx => {
    const { errors, isValid } = validateRegisterInput(ctx.request.body)
    if (!isValid) {
        ctx.status = 400
        ctx.body = errors
        return
    }

    // 存储到数据库
    const findResult = await User.find({ email: ctx.request.body.email });
    if (findResult.length > 0) {
        ctx.status = 500;
        ctx.body = { email: '邮箱已被占用' }
    } else {
        const avatar = gravatar.url(ctx.request.body.email, { s: '200', r: 'pg', d: 'mm' });
        const newUser = new User({
            name: ctx.request.body.name,
            email: ctx.request.body.email,
            password: tools.encrypt(ctx.request.body.password),//解决存入数据库的密码还是明文的问题
            avatar
        })
        //  加密 解决存入数据库的密码还是明文的问题
        // await bcrypt.genSalt(10, (err, salt)=> {
        //     bcrypt.hash(newUser.password, salt, (err, hash)=> {
        //         // Store hash in your password DB.
        //         if(err) throw err;
        //         newUser.password=hash
        //     });
        // });
        // 存储到数据库

        await newUser.save()
            .then(user => {
                ctx.status = 200
                ctx.body = user
            })
            .catch(err => console.log(err))
    }
})

/**
 * @route POST api/users/login
 * @desc 用户登录接口
 * @access 接口公开的
 */
router.post('/login', async ctx => {

    // 参数验证
    const { errors, isValid } = validateLoginInput(ctx.request.body)
    if (!isValid) {
        ctx.status = 400
        ctx.body = errors
        return
    }
    // 存储到数据库
    const findResult = await User.find({ email: ctx.request.body.email });
    const user = findResult[0]
    const password = ctx.request.body.password
    if (findResult.length > 0) {
        // 查到后验证密码
        let result = await bcrypt.compareSync(password, user.password);
        // 验证通过
        if (result) {
            const payload = { id: user.id, email: user.email, avatar: user.avatar, name: user.name }
            const token = jwt.sign(payload, keys.secretOrKey);
            ctx.status = 200
            ctx.body = { success: true, token: 'Bearer ' + token }
        } else {
            ctx.status = 400
            ctx.body = { password: "密码错误" }
        }
    } else {
        ctx.status = 404;
        ctx.body = { email: '用户不存在' }
    }
})
/*
* @route GET api/users/current
* @desc 获取当前用户信息
* @access 私密接口
*/
router.get('/current', passport.authenticate('jwt', { session: false }), async ctx => {
    let user = ctx.state.user
    ctx.body = {
        id: user.id, email: user.email, avatar: user.avatar, name: user.name
    }
})



module.exports = router.routes();